﻿using AutoMapper;
using RestApp.UI.Core;
using RestApp.UI.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using models = RestApp.UI.Models;

namespace RestApp.UI.Controllers
{
    [Authorize]
    public class JobFactsController : Controller
    {
        private IBusinessFactory _factory;
        public JobFactsController(IBusinessFactory factory)
        {
            _factory = factory;
        }

        [Authorize(Roles = "Manager")]
        public ActionResult Index(DateTime? dateFacts)
        {
            DateTime onDate = dateFacts ?? DateTime.Now;
            ViewData["onDate"] = onDate.ToShortDateString();
            var users = _factory.UsersLogic.GetWorkingUsersOnDate(onDate, User.Identity.Name);
            var mappedUsers = Mapper.Map<IEnumerable<models.User>>(users);
            return View(mappedUsers);
        }

        [Authorize(Roles = "Manager,User")]
        public ActionResult FillFacts(int id)
        {
            var user = _factory.UsersLogic.GetById(id);
            var mappedUser = Mapper.Map<models.User>(user);
            return View(mappedUser);
        }

        [Authorize(Roles = "User")]
        public ActionResult CurrentUserJobFacts(int idGraphic)
        {
            var currentUser = _factory.UsersLogic.GetByLogin(User.Identity.Name);
            if (currentUser == null)
            {
                return HttpNotFound();
            }
            var graphic = _factory.WorkGraphicLogic.GetById(idGraphic);
            if (graphic == null)
            {
                return RedirectToAction("FillFacts", new { id = currentUser.Id });
            }
            ViewData["idGraphic"] = idGraphic;
            return View();
        }

        [Authorize(Roles = "Manager")]
        public ActionResult FillTime(int idGraphic, int idUser)
        {
            var user = _factory.UsersLogic.GetById(idUser);
            if (user == null)
            {
                return HttpNotFound();
            }
            var graphic = _factory.WorkGraphicLogic.GetById(idGraphic);
            if (graphic == null)
            {
                return HttpNotFound();
            }
            ViewData["idGraphic"] = idGraphic;
            ViewData["idUser"] = idUser;
            ViewData["userName"] = string.Format("{0} {1} {2}", user.LastName, user.FirstName, user.MiddleName);
            ViewData["graphicDate"] = string.Format("{0} ({1} - {2})", new DateTime(graphic.Year.Value, graphic.Month.Value, graphic.Day.Value).ToShortDateString()
                , string.Format("{0:hh\\:mm}", graphic.StartTime)
                , string.Format("{0:hh\\:mm}", graphic.EndTime));
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Manager")]
        public ActionResult FillTime(JobFact jobFact, int idUser)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Пожалуйста, заполните форму корректными данными");
                ViewData["idGraphic"] = jobFact.IdWorkGraphic;
                ViewData["idUser"] = idUser;
                return View(jobFact);
            }
            if(jobFact.NormWork)
            {
                var graphic = _factory.WorkGraphicLogic.GetById(jobFact.IdWorkGraphic);
                jobFact.TimeStart = graphic.StartTime.Value;
                jobFact.TimeEnd = graphic.EndTime.Value;
                _factory.JobFactsLogic.Add(jobFact.ToBusinessEntity());
                return RedirectToAction("FillFacts", new { id = idUser });
            }
            if (jobFact.IsReasondForWorkCancelation)
            {
                if (string.IsNullOrEmpty(jobFact.Comment))
                {
                    ModelState.AddModelError("", "В случае уважительной причины отсутствия на работе, укажите данную причину в комментарии");
                    ViewData["idGraphic"] = jobFact.IdWorkGraphic;
                    ViewData["idUser"] = idUser;
                    return View(jobFact);
                }
                if (jobFact.NoWork)
                {
                    ModelState.AddModelError("", "Пожалуйста, выберите один из вариантов: уважительная причина отсутствия на работе или прогул.");
                    ViewData["idGraphic"] = jobFact.IdWorkGraphic;
                    ViewData["idUser"] = idUser;
                    return View(jobFact);
                }
            }
            else if (jobFact.NoWork)
            {
                if (jobFact.TimeEnd != null || jobFact.TimeStart != null)
                {
                    ModelState.AddModelError("", "В случае прогула не нужно заполнять время прихода/ухода");
                    ViewData["idGraphic"] = jobFact.IdWorkGraphic;
                    ViewData["idUser"] = idUser;
                    return View(jobFact);
                }
            }
            else
            {
                if (jobFact.TimeEnd == null || jobFact.TimeStart == null)
                {
                    ModelState.AddModelError("", "Пожалуйста, заполните время прихода/ухода сотрудника");
                    ViewData["idGraphic"] = jobFact.IdWorkGraphic;
                    ViewData["idUser"] = idUser;
                    return View(jobFact);
                }
            }
            _factory.JobFactsLogic.Add(jobFact.ToBusinessEntity());
            return RedirectToAction("FillFacts", new { id = idUser });
        }
    }
}